package com.migu.spms.service.impl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.migu.spms.common.JsonTool;
import com.migu.spms.common.ServiceProperties;
import com.migu.spms.common.StringUtil;
import com.migu.spms.constant.Constant;
import com.migu.spms.constant.FlowOperateMapping;
import com.migu.spms.dao.entity.ChangeHistoryDO;
import com.migu.spms.dao.entity.FunctionRequireDO;
import com.migu.spms.dao.inf.IChangeHistoryDO;
import com.migu.spms.dao.inf.IFunctionRequireDO;
import com.migu.spms.dao.inf.IProjectDO;
import com.migu.spms.message.constants.EmailTemplatePath;
import com.migu.spms.message.constants.MessageHandler;
import com.migu.spms.message.entity.MailMsgEntity;
import com.migu.spms.message.entity.MsgEntity;
import com.migu.spms.message.inf.JmsProducerService;
import com.migu.spms.service.data.EmailInfo;
import com.migu.spms.service.inf.IEmailService;
import com.migu.spms.service.inf.IUserInfoService;

@Component("emailServiceImpl")
public class EmailServiceImpl extends PublicService implements IEmailService {

	private static Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
	private static SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd");
	@Resource(name = "userInfoService")
    IUserInfoService userService;
	
	@Resource(name="queueSender")
	private JmsProducerService queueSender;
	
	@Value("${public_access_address}")
	private String public_access_address;
	
	@Autowired
	protected ServiceProperties sProperties;
	
	@Resource(name="IChangeHistoryDO")
	private IChangeHistoryDO historyDao;
	
	@Resource(name = "IFunctionRequireDO")
	private IFunctionRequireDO functionRequireDao;
	
	@Resource(name = "IProjectDO")
	private IProjectDO projectDAO;
	
    @Override
    public void sendBacklog(EmailInfo email){
        String currentStatus = email.getStatus();
        String title = acquireTitleByStatus(currentStatus);
        ChangeHistoryDO lastApprovalInfo=historyDao.selectLastFlowChangeEvent(email.getApplyId());
        if(!StringUtil.isEmpty(lastApprovalInfo.getCreateName())){
        	email.setUpperName(lastApprovalInfo.getCreateName());
        	email.setOperateEvent(FlowOperateMapping.getChineseOperate(lastApprovalInfo.getOperateType()));
        	email.setUpdateTime(formate.format(lastApprovalInfo.getCreateTime()));
        }
        email.setTitle(title);
        this.sendNotifyMail(email);
    }


	private String acquireTitleByStatus(String status) {
        String title = "";
        switch (status) {
        case Constant.flowStatus.NEWING:
            title = "功能需求处于新建阶段,请处理";
            break;
        case Constant.flowStatus.DEVELOPING:
            title = "功能需求处于开发中阶段，请处理";
            break;
        case Constant.flowStatus.TRANFER_TEST:
            title = "功能需求处于转测试阶段，请处理";
            break;
        case Constant.flowStatus.TESTING:
            title = "功能需求处于测试中阶段，请处理";
            break;
        case Constant.flowStatus.IMPLEMENTED:
        	title = "功能需求已实现阶段，请处理";
        	break;
        case Constant.flowStatus.REOPEN:
        	title = "功能需求重新打开阶段，请处理";
        	break;
        default:
            break;
        }
        return title;
    }

    private void sendNotifyMail(EmailInfo permitDO) {
		logger.info("sendNotifyMail:"+permitDO.getTitle()+"->"+permitDO.getCurrent_user_name()+":"+permitDO.getCurrent_user_id());
		Long id=permitDO.getApplyId();
		FunctionRequireDO permitApplyInfo=functionRequireDao.selectByPrimaryKey(id);
		String fucntionrequirementId=permitApplyInfo.getRequireId();
		String title="【咪咕开发云】功能需求模块提醒--功能需求编号【"+fucntionrequirementId+"】--"+permitDO.getTitle();
		String projectName=projectDAO.selectProjectNameById(String.valueOf(permitApplyInfo.getProjectId()));
		String url = public_access_address+ "/spms/static/function/index.html#"+permitApplyInfo.getProjectId()+"/"+projectName+"/functionDetail?id="+id+"&requireId="+fucntionrequirementId;
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("url", url);
		model.put("title", "项目组【"+projectName+"】  功能需求编号【"+fucntionrequirementId+"】  "+permitDO.getTitle());
		model.put("creatorName", permitApplyInfo.getCreatorName());
		model.put("curStatus", FlowOperateMapping.getChineseStatus(permitDO.getStatus()));
		model.put("upperName", permitDO.getUpperName());
		model.put("operateEvent", permitDO.getOperateEvent());
		model.put("updateTime", permitDO.getUpdateTime());
		
		//设置邮件模板属性变量  
		MailMsgEntity mailMsgEntity = new MailMsgEntity();
		mailMsgEntity.setTitle(title);
		mailMsgEntity.setUserId(String.valueOf(permitDO.getCurrent_user_id()));
		mailMsgEntity.setModel(model);
		//通知邮件模板
		mailMsgEntity.setTemplatePath(EmailTemplatePath.PERMIT_EMAIL_TEMPLATE);
		//邮件消息体
		MsgEntity msgEntity = new MsgEntity();
		msgEntity.setMsgBody(JsonTool.dataToJson(mailMsgEntity));
		msgEntity.setMsgHandler(MessageHandler.COMMON_MAIL_MSG_HANDLER);
		String sendMsg = JsonTool.dataToJson(msgEntity);
		logger.info("发送的邮件消息："+sendMsg);
		try {
			queueSender.sendMailMessage(sendMsg);
		} catch (Exception e) {
			logger.error(e.toString());
		}
		
	}
    
}
